import air.update.events.StatusUpdateErrorEvent;
import air.update.events.StatusUpdateEvent;
import air.update.events.UpdateEvent;

import com.nstar.base.controls.AlertX;
import com.nstar.base.event.RequestEvent;
import com.nstar.base.util.CSSParser;
import com.nstar.base.util.LoadXMLDelegate;
import com.nstar.base.util.Logger;
import com.nstar.base.util.StringUtils;
import com.nstar.splus.components.About;
import com.nstar.splus.components.BgImage;
import com.nstar.splus.components.FadeToolTip;
import com.nstar.splus.components.HintTextArea;
import com.nstar.splus.components.HotWindow;
import com.nstar.splus.components.ImageViewer;
import com.nstar.splus.components.InfoNumber;
import com.nstar.splus.components.MessageInput;
import com.nstar.splus.components.MicroBlogList;
import com.nstar.splus.components.OptionWindow;
import com.nstar.splus.components.OptionsMenu;
import com.nstar.splus.components.Pager;
import com.nstar.splus.components.PopUpMsgWindow;
import com.nstar.splus.components.PopUpTip;
import com.nstar.splus.components.ProgressInfo;
import com.nstar.splus.components.SearchBar;
import com.nstar.splus.components.UserProfileImage;
import com.nstar.splus.components.VersionCheck;
import com.nstar.splus.model.MicroMsgCommentItemCache;
import com.nstar.splus.model.MicroMsgItemCache;
import com.nstar.splus.model.MicroMsgPrivateItemCache;
import com.nstar.splus.model.OptionVO;
import com.nstar.splus.model.UpdateUtil;
import com.nstar.splus.model.Utils;
import com.nstar.splus.msgitem.MicroMsgItem;
import com.sina.microblog.MicroBlog;
import com.sina.microblog.data.MicroBlogComment;
import com.sina.microblog.data.MicroBlogDirectMessage;
import com.sina.microblog.data.MicroBlogRateLimit;
import com.sina.microblog.data.MicroBlogRelationshipDescriptor;
import com.sina.microblog.data.MicroBlogStatus;
import com.sina.microblog.data.MicroBlogUser;
import com.sina.microblog.data.MicroBlogUsersRelationship;
import com.sina.microblog.events.MicroBlogErrorEvent;
import com.sina.microblog.events.MicroBlogEvent;

import flash.data.EncryptedLocalStore;
import flash.desktop.ClipboardFormats;
import flash.desktop.DockIcon;
import flash.desktop.NativeApplication;
import flash.desktop.NotificationType;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.NativeWindow;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.InvokeEvent;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.NativeDragEvent;
import flash.events.NativeWindowDisplayStateEvent;
import flash.events.ProgressEvent;
import flash.filesystem.File;
import flash.geom.Point;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.SharedObject;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.navigateToURL;
import flash.system.Capabilities;
import flash.ui.Keyboard;
import flash.utils.ByteArray;

import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import mx.collections.IList;
import mx.containers.Canvas;
import mx.containers.TabNavigator;
import mx.containers.VBox;
import mx.controls.Button;
import mx.controls.Label;
import mx.controls.Text;
import mx.core.FlexLoader;
import mx.core.UITextField;
import mx.effects.Move;
import mx.events.CloseEvent;
import mx.events.EffectEvent;
import mx.events.ItemClickEvent;
import mx.events.ResizeEvent;
import mx.graphics.codec.JPEGEncoder;
import mx.managers.DragManager;
import mx.rpc.events.FaultEvent;
import mx.utils.ObjectUtil;


private var userName:String;
private var userPassword:String;
private var savePassword:String = "N";
private var microBlogAPI:MicroBlog;

private var accessTokenKey:String;
private var accessTokenSecrect:String;

//数据加载的起始ID
private var publicSinceID:uint = 0;
private var friendSinceID:uint = 0;
private var mentionSinceID:uint = 0;
private var commentSinceID:uint = 0;
private var dmrSinceID:uint = 0;
private var userSinceId:uint = 0;

//共享数据保存
private var so:SharedObject ;
private var soUrl:String = "splus/private";

//附件图片信息
private var imageName:String;
private var imageSize:Number;
private var imageByteArray:ByteArray;

private var logger:Logger = Logger.getInstance();

public var mbUser:MicroBlogUser;//当前登录用户
public var logined:Boolean = false;//是否已经登录
public var fetchSize:int = OptionVO.DEFAULT_FETCH_SIZE;//每次获取的最大消息数

private var selectedUser:MicroBlogUser;//当前选择记录的用户
private var vInterval:uint = 0;//定时刷新
private var vSecs:uint = OptionVO.DEFAULT_INTERVAL;//定时刷新 时间间隔，默认为40秒
private var vPopUpDelay:int = OptionVO.DEFAULT_POPUP_DELAY;//弹出窗口消息停留时间


private var autoLogin:Boolean = OptionVO.DEFAULT_AUTO_LOGIN;//是否自动登录
private var runOnStart:Boolean = OptionVO.DEFAULT_RUN_ON_START;//是否开机运行
private var autoRefresh:Boolean = true;//是否自动刷新
public var popupMsgTip:Boolean = OptionVO.DEFAULT_POPUP_TIP;//是否弹出提示信息窗口，弹出窗口可以设置，所以这里设置为public
private var soundTip:Boolean = OptionVO.DEFAULT_SOUND_TIP;//新消息声音提示
private var listFontSize:Number = OptionVO.DEFAULT_FONT_SIZE;//列表默认字体大小
public var appAlpha:Number = OptionVO.DEFAULT_APP_ALPHA;//应用透明度
public var useBgImage:Boolean = false;//是否使用背景图片
public var dingUrl:String = OptionVO.DEFAULT_DING_URL;//声音提示文件位置
public var useCustomTipSound:Boolean = OptionVO.DEFAULT_USE_CUSTOM_TIP_SOUND;//使用自定义提示音
private var autoSnap:Boolean = OptionVO.DEFAULT_AUTO_SNAP;//是否自动吸附窗口

private var info:String  = "";//提示信息

private var updateUtil:UpdateUtil;//自动升级处理


//窗口自动吸附处理
public static const SNAP_TOP:String = "snapTop";
public static const SNAP_LEFT:String = "snapLeft";
public static const SNAP_RIGHT:String = "snapRight";

public static const LOAD_USER_OK:String = "loadUserOk";

public static const TAB_BUTTON_WIDTH:int = 42;
//窗口自动吸附的最小距离
private var snapDistance:Number = 5;
//最小移动距离
private var minMovedSize:Number = 10;
private var oldX:Number;
private var oldY:Number;

private var isSnaped:Boolean = false;//是否已经自动吸附
private var isMoved:Boolean = false;
private var snapDirection:String ;//窗口吸附的方位
private var firstRun:Boolean = true;//是否首次运行
private var showUserMicroBlog:Boolean = false;//显示指定用户微博
private var reloadAll:Boolean = false;//重取列表消息
private var autoCheck:Boolean;//是否为自动检测版本
private var showUserPopup:Boolean = true;//是否显示获取用户信息后的弹出窗口
private var isPaging:Boolean = false;//是否正在翻页显示
private var maxed:Boolean = false;//是否已经最大化
private var isPopUpText:Boolean = false;//是否弹出了转发或评论窗口，用于处理自动隐藏后转发和评论的窗口隐藏问题
private var alwaysInFrontFlag:Boolean = false;//窗口置顶

private var followersCount:int = 0;

//微博消息翻页及游标
private var friendPage:int = 1;
private var atMePage:int = 1;
private var commentsPage:int = 1;
private var directMsgPage:int = 1;
private var myFavoritePage:int = 1;
private var usersPage:int = 1;

private var loader:LoadXMLDelegate;
//通知文件URL
private var noticeUrl:String = "http://snaildesign.googlecode.com/files/notices.xml";
private var updateUrl:String = "http://snaildesign.googlecode.com/files/update.xml";
private var backgroundImageUrl:String = "";

//应用初始化-//1717946245,"半杯咖啡Flex"
private function init():void{
	//如果有通知信息，加载之
	loadNotice();
	//检查新版本
	checkVersion();
	//加载本地配置
	so = SharedObject.getLocal(soUrl);
	loadConfig(); 
	
	//如果使用的背景图片，则使用蒙板来庶罩
	if(useBgImage){
		//添加背景蒙板
		addBgMask();
	}
	
	microBlogAPI = Utils.getMicroBlog();
	
	loginPanel.addEventListener(LoginPanel.LOGIN,loginHandler);
	loginPanel.addEventListener(LoginPanel.OAUTH_REQUEST,oauthRequestHandler);
	loginPanel.addEventListener(LoginPanel.OAUTH_LOGIN,oauthLoginHandler);
	//添加微博对象事件侦听器
	addMicroBlogEventListeners();
	
	initButtonIcon();
	bbControl.addEventListener(ItemClickEvent.ITEM_CLICK,changeHandler,false,0,true);
//	this.addEventListener(Event.ACTIVATE,activeHandler);
	this.addEventListener(Event.CLOSING,closingHandler);
	this.addEventListener(NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE,displayStateChangeHandler);
	//快捷键的处理
	this.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN,shortCutHandler);
//	this.addEventListener(ResizeEvent.RESIZE,resizeWinHandler);
	
	
	//微博发布操作
	messageInput.addEventListener(MessageInput.INSERT_IMAGE,insertImage,false,0,true);
	messageInput.addEventListener(MessageInput.PUBLISH,publishHandler,false,0,true);
	messageInput.addEventListener(MessageInput.CHANGE_SIZE,changeInputHandler,false,0,true);
	messageInput.addEventListener(HintTextArea.DELETE_IMAGE,deleteImageHandler,false,0,true);
	messageInput.addEventListener(MessageInput.PASTE_BMP,pasteBMPHandler,false,0,true);
	
	//支持图片文件的拖入作为消息的附件
    this.addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER,dragHandler);
    this.addEventListener(NativeDragEvent.NATIVE_DRAG_DROP,dragHandler);
    this.addEventListener(NativeDragEvent.NATIVE_DRAG_EXIT,dragHandler);
    //窗口自动吸附处理
	this.addEventListener(MouseEvent.ROLL_OVER,showMainWindow);
	this.addEventListener(MouseEvent.ROLL_OUT,showMainWindow);
	
	this.addEventListener(MicroBlogList.POP_UP_WIN,popUpWinHandler);
	this.addEventListener(MicroBlogList.HIDE_POP_UP_WIN,popUpWinHandler);
	
	//显示用户头像
	this.addEventListener("showProfileImage",showProfileImageHandler);
	this.addEventListener("hideProfileImage",showProfileImageHandler);
	
	
	infoHome.addEventListener(InfoNumber.READALL,readAllHandler,false,0,true);
	infoAtMe.addEventListener(InfoNumber.READALL,readAllHandler,false,0,true);
	infoComment.addEventListener(InfoNumber.READALL,readAllHandler,false,0,true);
	infoDirectMsg.addEventListener(InfoNumber.READALL,readAllHandler,false,0,true);
	infoUser.addEventListener(InfoNumber.READALL,readAllHandler,false,0,true);
    
    listFriends.addEventListener(MicroBlogList.NEW_MSG_COUNT,showNewMsgCountHandler,false,0,true);
    listComments.addEventListener(MicroBlogList.NEW_MSG_COUNT,showNewMsgCountHandler,false,0,true);
    listPrivate.addEventListener(MicroBlogList.NEW_MSG_COUNT,showNewMsgCountHandler,false,0,true);
    
//    pager = Pager.show();
	pager.addEventListener(Pager.GET_PAGE,pagerHandler,false,0,true);
	pager.addEventListener(Pager.SEND_PAGE,pagerHandler,false,0,true);
    pager.addEventListener(Pager.FIRST_PAGE,pagerHandler,false,0,true);
    pager.addEventListener(Pager.PRIOR_PAGE,pagerHandler,false,0,true);
    pager.addEventListener(Pager.NEXT_PAGE,pagerHandler,false,0,true);
    
//    messageInput.addEventListener(ResizeEvent.RESIZE,resetPagerHandler);
    
    //判断是否为自动登录
    if(autoLogin){
    	loginPanel.loginHandler(null);
    }
    
}

 

//支持图片的拖拽操作
private function dragHandler(event:NativeDragEvent):void{
	
	switch(event.type){
		case NativeDragEvent.NATIVE_DRAG_ENTER:
			DragManager.acceptDragDrop(this);
			break;
		case NativeDragEvent.NATIVE_DRAG_DROP:
			var dropFiles:Array = event.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
			
			if(!checkDragFile(dropFiles)){
				FadeToolTip.show(mbUser.screenName+",注意只支持JPG,PNG,GIF图片格式的文件!");
				return;				
			}
						
            if(dropFiles.length>1){
            	FadeToolTip.show(mbUser.screenName+",现在只支持拖入一张图片。");
            	return;
            }
            
            imageByteArray = new ByteArray();
            for each(var file:File in dropFiles){
            	readImageFile(file);
            }
			break;
		case NativeDragEvent.NATIVE_DRAG_EXIT:
			trace("Drag exit event.");
			break;
	}
}



//选项下拉菜单处理
private function changeMenuHandler(event:RequestEvent):void{
	this.addShowWindowHandler(null);
	var menuItem:Object = event.request;
	var index:int = int(menuItem.index);
	switch(index){
		case 1://设置...
			OptionWindow.show();
			break;
		case 2://切换用户
			microBlogAPI.logout();
			vsTitle.selectedIndex = 0;
			vsControl.selectedIndex = 0;
			loginPanel.txtUser.setFocus();
			loginPanel.btnLogin.enabled = true;
			boxFooter.visible = boxFooter.includeInLayout = false;
			
			break;
		case 3://检查新版本
			checkVersion(false);
			break;
		case 4://你有什么意见或建议？
			var mi:MessageInput = MessageInput.show(10,38,"您有什么意见和建议？");
			mi.addEventListener(MessageInput.INSERT_IMAGE,insertImage);
			mi.addEventListener(MessageInput.PUBLISH,adviceHandler);
			break;
		case 5://访问新浪首页
			navigateToURL(new URLRequest("http://t.sina.com.cn"),"_blank");
			break;
		case 6://关于...
			About.show();
			break;
		case 7://退出
			exitHandler();
			break;
	}
}

//检查拖入的文件
private function checkDragFile(files:Array):Boolean{
	for each(var file:File in files){
		switch(file.extension.toUpperCase()){
			case "JPG":
			case "PNG":
			case "GIF":
				return true;
			default:
				return false;
		}
	}
	return false;
}

//定时检查消息更新
private function refreshHandler():void{
	trace("auto refresh ...");
	showUserMicroBlog = false;
	reloadAll = false;
	isPaging = false;
	info = "";
	refresh(0);//关注者
	//refresh(1);//@me
	refresh(2);//评论
	refresh(3);//私信
	
	loadUserInfo(mbUser.screenName,false);//获取用户信息，例如新增粉丝
}

public function refreshButtonHandler(reload:Boolean=false):void{
	showProgressBar(true);
	showUserMicroBlog = false;
	if(vsMain.selectedIndex==6){//随便看看的强制刷新
		refresh(vsMain.selectedIndex,true);
	}else{
		refresh(vsMain.selectedIndex,true);
	}
	
}

//签到
public function signInHandler():void{
//	var s:String = "签到："+DateUtils.monthDayCn()+" "+DateUtils.nowSegment();
//	messageInput.message = s;
}

//添加微博对象事件侦听器
private function addMicroBlogEventListeners():void{
	//用户认证
	microBlogAPI.addEventListener(MicroBlogEvent.VERIFY_CREDENTIALS_RESULT, loginSucessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.VERIFY_CREDENTIALS_ERROR, loginErrorHandler,false,0,true);
	//返回用户所有关注的用户最新的n条微博消息
	microBlogAPI.addEventListener(MicroBlogEvent.LOAD_FRIENDS_TIMELINE_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.LOAD_FRIENDS_TIMELINE_ERROR,loadErrorHandler,false,0,true);
	//提及我的微博
	microBlogAPI.addEventListener(MicroBlogEvent.LOAD_MENSIONS_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.LOAD_MENSIONS_ERROR,loadErrorHandler,false,0,true);
	//我的评论
	microBlogAPI.addEventListener(MicroBlogEvent.LOAD_MY_COMMENTS_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.LOAD_MY_COMMENTS_ERROR,loadErrorHandler,false,0,true);

	microBlogAPI.addEventListener(MicroBlogEvent.LOAD_COMMENTS_TIMELINE_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.LOAD_COMMENTS_TIMELINE_ERROR,loadErrorHandler,false,0,true);
	//我收到的私信
	microBlogAPI.addEventListener(MicroBlogEvent.LOAD_DIRECT_MESSAGES_RECEIVED_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.LOAD_DIRECT_MESSAGES_RECEIVED_ERROR,loadErrorHandler,false,0,true);
	//我发出的私信
	microBlogAPI.addEventListener(MicroBlogEvent.LOAD_DIRECT_MESSAGES_SENT_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.LOAD_DIRECT_MESSAGES_SENT_ERROR,loadErrorHandler,false,0,true);
	//我的收藏
	microBlogAPI.addEventListener(MicroBlogEvent.LOAD_FAVORITE_LIST_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.LOAD_FAVORITE_LIST_ERROR,loadErrorHandler,false,0,true);
	//当前用户的信息
	microBlogAPI.addEventListener(MicroBlogEvent.LOAD_USER_INFO_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.LOAD_USER_INFO_ERROR,loadErrorHandler,false,0,true);
	//加载公共发布的信息，用于登录前的显示
	microBlogAPI.addEventListener(MicroBlogEvent.LOAD_PUBLIC_TIMELINE_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.LOAD_PUBLIC_TIMELINE_ERROR,loadErrorHandler,false,0,true);
	//发布新微博
	microBlogAPI.addEventListener(MicroBlogEvent.UPDATE_STATUS_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.UPDATE_STATUS_ERROR,loadErrorHandler,false,0,true);

	//检查与某个用户的Follow关系
	microBlogAPI.addEventListener(MicroBlogEvent.CHECK_IS_FOLLOWING_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.CHECK_IS_FOLLOWING_ERROR,loadErrorHandler,false,0,true);
	//返回指定用户的微博列表
	microBlogAPI.addEventListener(MicroBlogEvent.LOAD_USER_TIMELINE_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.LOAD_USER_TIMELINE_ERROR,loadErrorHandler,false,0,true);
	//统计微博的转发数，评论数
	microBlogAPI.addEventListener(MicroBlogEvent.LOAD_STATUS_COUNTS_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.LOAD_STATUS_COUNTS_ERROR,loadErrorHandler,false,0,true);

	//获取当前的API调用次数限制
	microBlogAPI.addEventListener(MicroBlogEvent.GET_RATE_LIMIT_STATUS_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.GET_RATE_LIMIT_STATUS_ERROR,loadErrorHandler,false,0,true);

	microBlogAPI.addEventListener(MicroBlogEvent.LOAD_STATUS_INFO_RESULT,loadSuccessHandler,false,0,true);
	microBlogAPI.addEventListener(MicroBlogErrorEvent.LOAD_STATUS_INFO_ERROR,loadErrorHandler,false,0,true);
}

//如果窗口隐藏了，则移出来
private function activeHandler(event:Event):void{
	if(isSnaped){
		isSnaped = false;
		this.alwaysInFront = true;
		showWindow();
	}
}

//关闭窗口前，把其它打开的窗口都关闭掉
private function closingHandler(event:Event):void{
	var idx:int = 0;
	for each(var window:NativeWindow in  this.nativeApplication.openedWindows){
		if(idx!=0){
			window.close();
		}
		idx++;
	}
}

//最大化、最小化切换
private function displayStateChangeHandler(event:NativeWindowDisplayStateEvent):void{
	if(event.afterDisplayState=="minimized"){
		this.minimize();
	}
}

//隐藏消息数提示
private function hideInfoNumber():void{
	switch(bbControl.selectedIndex){
		case 0:
			infoHome.hide();
			break;
		case 1:
			infoAtMe.hide();
			break;
		case 2:
			infoComment.hide();
			break;
		case 3:
			infoDirectMsg.hide();
			break;
		case 4:
			break;
	}
}

//初始化主按钮图标
private function initButtonIcon():void{
	var idx:int = 0;
	var icons:Array = [".home",".mine",".comment",".directMsg",".favorite",".user",".public"];
	for each(var button:Button in bbControl.getChildren()){
		button.label = "";
		button.width = TAB_BUTTON_WIDTH;
		button.setStyle("paddingLeft",0);
		button.setStyle("paddingRight",0);
		button.setStyle("icon",CSSParser.getStyle(icons[idx],"icon"));
		idx++;
	}
}

//加载指定用户的微博消息
public function loadUserTimeline(screenName:String):void{
	showUserMicroBlog = true;
	showProgressBar(true);
	microBlogAPI.loadUserTimeline(null,0,screenName);
}

//取列表对象
private function getMicroBlogList(index:int):MicroBlogList{
	var item:DisplayObject = vsMain.getChildAt(index);
	if(item is MicroBlogList){
		return MicroBlogList(item);
	}else{//我的微博列表，里面包含了用户信息和MicroBlogList
		return MicroBlogList(VBox(item).getChildAt(1));
	}
}

//按钮切换
private function changeHandler(event:ItemClickEvent):void{
	isPaging = false;
	showUserMicroBlog = false;
	showProgressBar(true);
	refresh(event.index);
	pager.setButtonVisible(getMicroBlogList(event.index).page);
	pager.showRecSend(event.index==3);//私信显示另外两个按钮
	//以下处理是防止同样的事件在不同的列表里被处理
	//先删除列表对微博消息的监听事件
	removeAllMicroBlogListener1();
	//给当前列表添加微博消息监听事件
	addMicroBlogListener1(event.index);
	
	pager.visible = (event.index!=6);
}

//设置不同列表切换时的翻页按钮可见性
private function setPageButtonVisible(index:int):void{
	var item:MicroBlogList = getMicroBlogList(index);
	pager.setButtonVisible(item.page);
}


//删除列表的监控事件
private function removeAllMicroBlogListener1():void{
	var idx:int = 0;
	for each(var item:Object in vsMain.getChildren()){
		getMicroBlogList(idx++).removeMicroBlogListener1();
	}
}

//添加列表的监控事件
private function addMicroBlogListener1(index:int):void{
	var item:MicroBlogList = getMicroBlogList(index);
	item.addMicroBlogListener1();
}

//刷新列表数据，刷新 时每次都查最新的,reload表示是否重新从sinceID=0获取
private function refresh(index:int,reload:Boolean=false):void{
	reloadAll = reload;
	//如果没有登录则取公共微博信息
	if(!logined){
		microBlogAPI.loadPublicTimeline();
		return;
	}
	switch(index){
		case 0://我关注的人微博
			microBlogAPI.loadFriendsTimeline(reload?0:friendSinceID,0,fetchSize);//friendSinceID
			break;
		case 1://提及我的微博
			microBlogAPI.loadMentions(reload?0:mentionSinceID,0,fetchSize);//mentionSinceID
			break;
		case 2://我的评论
			//microBlogAPI.loadMyComments(reload?0:commentSinceID,0,fetchSize);//commentSinceID
			microBlogAPI.loadCommentsTimeline(reload?0:commentSinceID,0,fetchSize);//commentSinceID
			break;
		case 3://发给我的私信
			microBlogAPI.loadDirectMessagesReceived(reload?0:dmrSinceID,0,fetchSize);//dmrSinceID
			break;
		case 4://我的收藏
			microBlogAPI.loadFavoriteList();
			break;
		case 5://默认为我的微博
			microBlogAPI.loadUserTimeline(null,selectedUser.id,selectedUser.screenName,
				reload?0:userSinceId,0,fetchSize);
			break;
		case 6://随便看看
			if(listPublic.dataProvider==null || reload == true){
				microBlogAPI.loadPublicTimeline();
			}else{
				showProgressBar(false);
			}
			break;
	}
}


//成功处理数据
private function loadSuccessHandler(event:MicroBlogEvent):void{
	showProgressBar(false);
	var tmpList:ArrayList;
	switch(event.type){
		case MicroBlogEvent.LOAD_FRIENDS_TIMELINE_RESULT://返回用户所有关注的用户最新的n条微博消息
			//MicroBlogStatus
			pager.setEnabled(true);
			listFriends.user = mbUser;
			tmpList =  new ArrayList(event.result as Array);
			var tmpFriendSinceID:uint = getSinceID(tmpList,friendSinceID);
			var newCount:int = refreshDataProvider(listFriends,tmpList);
			if(isPaging==false){
				//取到了相同的ID
				if(tmpFriendSinceID == friendSinceID){
					break;
				}
				friendSinceID = tmpFriendSinceID;
			}else{
				listFriends.verticalScrollPosition = 0;
			}
			//统计转发和评论数
			loadStatusInfoHandler(listFriends.dataProvider);
			//显示提示消息窗口，并在主程序窗口上以小图标显示消息数
			if(newCount>0 && reloadAll==false){
				//如果窗口是最小化的，则右下角弹出小窗口的方式显示新消息
				//如果当前窗口没有最小化，则闪烁任务栏来提醒
				if(this.nativeWindow.visible){
					//闪烁任务栏，并显示消息数
					if(firstRun){
						firstRun = false;
					}else{
						if(isMine(tmpList,event.type)==false){
							//播放声音提示
							if(soundTip && this.nativeWindow.active==false){
								this.nativeWindow.notifyUser(NotificationType.INFORMATIONAL);
								playDingDong();
							}
						}
					}
				}else{
					if(isMine(tmpList,event.type)==false){
						if(soundTip){
							playDingDong();
						}
						//弹出消息提示
						if(popupMsgTip){
							PopUpMsgWindow.show(tmpList.toArray());
						}
						//新消息图标
						addSysTrayIcon(true);
							
					}
				}
			}
			
			break;		
		case MicroBlogEvent.LOAD_MENSIONS_RESULT://提及我的微博
			pager.setEnabled(true);
			listAtMe.user = mbUser;
			tmpList =  new ArrayList(event.result as Array);
			var newCount:int = refreshDataProvider(listAtMe,tmpList);
			if(isPaging==false){
				mentionSinceID = getSinceID(tmpList,mentionSinceID);
			}else{
				listAtMe.verticalScrollPosition = 0;
			}
			break;
		case MicroBlogEvent.LOAD_MY_COMMENTS_RESULT://返回我的评论
		case MicroBlogEvent.LOAD_COMMENTS_TIMELINE_RESULT:
			//MicroBlogComment
			pager.setEnabled(true);
			listComments.user = mbUser;
			tmpList =  new ArrayList(event.result as Array);
			var isFirstComments:Boolean = (listComments.dataProvider==null);//是否第一次设置列表
			var newCount:int = refreshDataProvider(listComments,tmpList);
			var tmpCommentSinceID:uint = getSinceID(tmpList,commentSinceID);
			if(isFirstComments==false && isPaging==false && newCount>0 && popupMsgTip){
				//如果评论ID相同，则取到了相同的评论
				if(tmpCommentSinceID == commentSinceID){
					break;
				}
				if(isMine(tmpList,event.type)==false){
					popUpTip("您有"+newCount+"条新评论！");
					if(this.nativeWindow.visible==false){
						addSysTrayIcon(true);
					}
				}
			}

			
			if(isPaging==false){
				commentSinceID = tmpCommentSinceID;
			}else{
				listComments.verticalScrollPosition = 0;
			}
			
			break;
		case MicroBlogEvent.LOAD_DIRECT_MESSAGES_RECEIVED_RESULT://我接收到的私信
			//MicroBlogDirectMessage
			pager.setEnabled(true);
			listPrivate.user = mbUser;
			tmpList =  new ArrayList(event.result as Array);
			var isFirstDirectMsg:Boolean = (listPrivate.dataProvider==null);//是否第一次设置列表
			var newCount:int = refreshDataProvider(listPrivate,tmpList);
			var tmpDmrSinceID:uint = getSinceID(tmpList,dmrSinceID);
			if(isFirstDirectMsg==false && isPaging==false && newCount>0 && popupMsgTip){
				//如果私信ID相同，则取到了相同的私信
				if(tmpDmrSinceID == dmrSinceID){
					break;
				}
								
				popUpTip("您有"+newCount+"条新私信！");
				if(this.nativeWindow.visible==false){
					addSysTrayIcon(true);
				}
			}
						
			if(isPaging==false){
				dmrSinceID = tmpDmrSinceID;
			}else{
				listPrivate.verticalScrollPosition = 0;
			}
			break;
		case MicroBlogEvent.LOAD_DIRECT_MESSAGES_SENT_RESULT://我发出的私信
			pager.setEnabled(true);
			listPrivate.user = mbUser;
			tmpList =  new ArrayList(event.result as Array);
			var newCount:int = refreshDataProvider(listPrivate,tmpList);
			break;
		case MicroBlogEvent.LOAD_FAVORITE_LIST_RESULT://我的收藏列表
			//MicroBlogStatus
			pager.setEnabled(true);
			listFavorite.user = mbUser;
			tmpList =  new ArrayList(event.result as Array);
			var newCount:int = refreshDataProvider(listFavorite,tmpList);
			//统计转发和评论数
			loadStatusInfoHandler(listFavorite.dataProvider);
			break;
		case MicroBlogEvent.LOAD_USER_TIMELINE_RESULT://返回指定用户的微博列表
			pager.setEnabled(true);
			listUser.user = mbUser;
			tmpList =  new ArrayList(event.result as Array);
			var newCount:int = refreshDataProvider(listUser,tmpList);
			if(isPaging==false){
				userSinceId = getSinceID(tmpList,userSinceId);
			}else{
				boxUser.verticalScrollPosition = 0;
			}
			selectedUser = getSelectedUser(tmpList);
			//如果是主动查看用户的微博列表时，则切换到该列表下面
			if(showUserMicroBlog){
				userInfo.user = selectedUser;
				bbControl.selectedIndex = 5;
			}
			break;
		case MicroBlogEvent.LOAD_PUBLIC_TIMELINE_RESULT://加载公共微博信息，用于登录前的显示
			listPublic.user = mbUser;
			tmpList =  new ArrayList(event.result as Array);
			listPublic.dataProvider = tmpList;
			break;	
		/////////////////////////////////////////////////////////////////////////////////
		case MicroBlogEvent.UPDATE_STATUS_RESULT://发布新微博
			updateStatusSucessHandler(MicroBlogStatus(event.result));
			break;
		case MicroBlogEvent.LOAD_USER_INFO_RESULT://返回用户信息
			loadUserInfoSucessHandler(MicroBlogUser(event.result));
			break;
		case MicroBlogEvent.CHECK_IS_FOLLOWING_RESULT://返回与被检查用户之间的关系
			checkIsFlllowingSucessHandler(MicroBlogUsersRelationship(event.result));
			break;
		case MicroBlogEvent.LOAD_STATUS_COUNTS_RESULT://返回对微博的转发和评论数
			loadStatusCountsSucessHandler(event.result as Array);
			break;
		case MicroBlogEvent.GET_RATE_LIMIT_STATUS_RESULT://获取当前的API调用次数限制
			getRateLimitStatuSuccessHandler(event.result as MicroBlogRateLimit);
			break;
		case MicroBlogEvent.LOAD_STATUS_INFO_RESULT://获取指定微博消息
			updateCreateTime(event.result as MicroBlogStatus);
			break;
	}
	
	this.status = info;
	
}

//从返回的微博列表中取用户信息
private function getSelectedUser(list:ArrayList):MicroBlogUser{
	if(list && list.length>0){
		var sts:MicroBlogStatus = MicroBlogStatus(list.getItemAt(0));
		return sts.user;
	}else{
		return this.selectedUser;
	}
}

//检查新消息是否为我的消息
private function isMine(list:ArrayList,type:String):Boolean{
	var count:int = 0;
	switch(type){
		case MicroBlogEvent.LOAD_FRIENDS_TIMELINE_RESULT:
			for(var i:int =0;i<list.length;i++){
				if(MicroBlogStatus(list.getItemAt(i)).user.id == mbUser.id){
					count++;
				}
			}
			break;
		case MicroBlogEvent.LOAD_MY_COMMENTS_RESULT:
		case MicroBlogEvent.LOAD_COMMENTS_TIMELINE_RESULT:
			for(var i:int =0;i<list.length;i++){
				if(MicroBlogComment(list.getItemAt(i)).user.id == mbUser.id){
					count++;
				}
			}
			break;
		case MicroBlogEvent.LOAD_DIRECT_MESSAGES_RECEIVED_RESULT:
			for(var i:int =0;i<list.length;i++){
				if(MicroBlogDirectMessage(list.getItemAt(i)).senderID == mbUser.id){
					count++;
				}
			}		
			break;
	}
	
	
	return (count>0 && count==list.length);
}

//弹出提示信息
private function popUpTip(msg:String):void{
	//弹出有新评论提示
	if(reloadAll==false){
		//如果窗口是最小化的，则右下角弹出小窗口的方式显示新消息
		//如果当前窗口没有最小化，则闪烁任务栏来提醒
		if(this.nativeWindow.visible){
			//播放声音提示
			if(soundTip && this.nativeWindow.active==false){
				//闪烁任务栏，MEMO:切换到新列表时，列表索引获取不正确，因此先不切换到该列表
				this.nativeWindow.notifyUser(NotificationType.INFORMATIONAL);
				playDingDong();
			}						
		}else{
			if(soundTip){
				playDingDong();
			}
		}
		//弹出消息提示
		PopUpTip.show(msg);
	}			
}

//刷新数据源
private function refreshDataProvider(list:MicroBlogList,values:ArrayList):int{
	trace("msg list = "+values.length+",list="+list.name);
	var result:int = 0;
	//如果是翻页，则清空列表数据
	if(isPaging || this.showUserMicroBlog){
		trace("isPaging="+isPaging);
		list.dataProvider = values;
		result = values.length;
		if(showUserMicroBlog){
			isPaging = true;
		}
	}else{
		if(list.dataProvider){
			result = list.addItemListAt(values,true);
		}else{
			list.dataProvider = values ;
			result = values.length;
		}
	}
	
	return result;
}

//加载数据出现异常
private function loadErrorHandler(event:MicroBlogErrorEvent):void
{
	showProgressBar(false);
	trace("error->"+event.message);
	switch(event.type){
		case MicroBlogErrorEvent.UPDATE_STATUS_ERROR:
			FadeToolTip.show(mbUser.screenName+",发布微博失败！请稍候再试。");
			break;
		case MicroBlogErrorEvent.DELETE_STATUS_ERROR:
			FadeToolTip.show(mbUser.screenName+",删除微博失败！请稍候再试。");
			break;
		case MicroBlogErrorEvent.LOAD_USER_INFO_ERROR://加载用户信息失败
			FadeToolTip.show("未找到该用户！");
			break;
		default:
			FadeToolTip.show("处理微博消息出现异常，请稍候再试！");
			break;
	}
	
}

//保存配置
private function saveConfig():void{
	so.data["savePassword"] = savePassword;
	so.data["userName"]=userName;
	so.data["userPassword"] = "";
	
//	if(savePassword=="Y"){
//		so.data["userPassword"]=userPassword;
//	}else{
//		so.data["userPassword"]="";
//	}
	
	//保存到本地加密存储位置
	var passBytes:ByteArray = new ByteArray();
	passBytes.writeUTFBytes(userPassword);
	EncryptedLocalStore.setItem("password",passBytes);
	
	so.flush();
}

//从本地加载配置
private function loadConfig():void{
	savePassword = so.data["savePassword"];
	//用户名称始终需要保存的
	userName = so.data["userName"];
	
	var passBytes:ByteArray ;
	
	if(StringUtils.isEmpty(savePassword)){
		userPassword = "";
	}else{
		passBytes = EncryptedLocalStore.getItem("password");
		if(passBytes){
			userPassword = passBytes.readUTFBytes(passBytes.length);
		}else{
			userPassword = "";
		}
		
	}
	
	
	loginPanel.setUserPass(userName,userPassword,savePassword=="Y"?true:false);
	
	if(so.data["appWidth"]){
		this.width = so.data["appWidth"];
	}
	if(so.data["appHeight"]){
		this.height = so.data["appHeight"];
	}
	
	
	//加载选项设置
	loadOptions();
}

//加载选项设置
private function loadOptions():void{
	if(so.data["accessTokenKey"]){
		accessTokenKey = so.data["accessTokenKey"];
		accessTokenSecrect = so.data["accessTokenSecrect"];
	}
	
	//刷新时间
	if(so.data["refreshInterval"])
		vSecs = int(so.data["refreshInterval"]);
	//列表最大可显示消息数目
	
	if(so.data["listMaxCount"]){
		updateMaxCount(int(so.data["listMaxCount"]));
	}
	//消息弹出窗口停留时间
	if(so.data["popUpDelay"]){
		vPopUpDelay = int(so.data["popUpDelay"]);
	}
	
	if(so.data.hasOwnProperty("autoLogin"))
		autoLogin = so.data["autoLogin"];
	if(so.data.hasOwnProperty("runOnStart"))
		runOnStart = so.data["runOnStart"];
	if(so.data.hasOwnProperty("popupTip"))
		popupMsgTip = so.data["popupTip"];
	
	if(so.data.hasOwnProperty("soundTip"))
		soundTip = so.data["soundTip"];

	if(so.data.hasOwnProperty("fontSize"))
		listFontSize = so.data["fontSize"];
		
	if(so.data.hasOwnProperty("appAlpha"))
		appAlpha = so.data["appAlpha"];
		
	if(so.data.hasOwnProperty("useBgImage"))
		useBgImage = so.data["useBgImage"];
		
	if(so.data.hasOwnProperty("useCustomTipSound")){
		useCustomTipSound = so.data["useCustomTipSound"];
		if(useCustomTipSound==true){
			dingUrl = so.data["dingUrl"];
		}
	}
	
	if(so.data.hasOwnProperty("autoSnap"))
		autoSnap = so.data["autoSnap"];	
		

	this.alpha = appAlpha;
//	if(useBgImage){
//		this.setStyle("borderSkin",BgImage);
//		this.addBgMask();
//	}
		
	updateListFontSize(listFontSize);
	//是否开机启动
	if(!Capabilities.isDebugger){
		this.nativeApplication.startAtLogin = runOnStart;
	}
	
}

//更新列表最大可容纳消息数
private function updateMaxCount(maxCount:int):void{
	for each(var item:Object in vsMain.getChildren()){
		if(item is MicroBlogList){
			MicroBlogList(item).maxCount = maxCount;
		}else
		if(item is TabNavigator){
			for each(var tab:MicroBlogList in item.getChildren()){
				tab.maxCount = maxCount;
			}
		}
	}
}

private function updateListFontSize(size:Number):void{
	for each(var item:Object in vsMain.getChildren()){
		item.setStyle("fontSize",size);
	}
}


//用户登录
private function loginHandler(event:RequestEvent):void{
	microBlogAPI.accessTokenKey = "";
	microBlogAPI.accessTokenSecrect = "";
	microBlogAPI.pin = "";
	
	userName = String(event.request.userName);
	userPassword = String(event.request.userPass);
	savePassword = String(event.request.savePass);
	microBlogAPI.login(userName,userPassword);
	loginPanel.updateButtonStatus(false);
	showProgressBar(true,'正在登录...');//显示登录进度条
}

//使用Oauth方式登录请求
private function oauthRequestHandler(event:RequestEvent):void{
	microBlogAPI.consumerKey = Utils.APP_ID;
	microBlogAPI.consumerSecret = Utils.APP_SECRET;
	microBlogAPI.login();
}
//使用Oauth方式登录
private function oauthLoginHandler(event:RequestEvent):void{
	trace(microBlogAPI.accessTokenKey+","+microBlogAPI.accessTokenSecrect);
	microBlogAPI.pin = String(event.request);
}

//成功登录，加载提到我的微博
private function loginSucessHandler(event:MicroBlogEvent):void
{
	
	trace("login sucessful");
	trace(microBlogAPI.accessTokenKey+","+microBlogAPI.accessTokenSecrect);
	accessTokenKey = microBlogAPI.accessTokenKey;
	accessTokenSecrect = microBlogAPI.accessTokenSecrect;
	so.data["accessTokenKey"] = accessTokenKey;
	so.data["accessTokenSecrect"] = accessTokenSecrect;
	so.flush();
		
	logined = true;
	if(useBgImage){
		addBgMask();
	}
	
	showProgressBar(logined);//隐藏登录进度栏
	bbControl.visible = bbControl.includeInLayout = logined;
	messageInput.visible = messageInput.includeInLayout = logined;
	boxFooter.visible = boxFooter.includeInLayout = logined;
	
	mbUser = MicroBlogUser(event.result);//登录用户信息
	userPanel.user = mbUser;//显示用户信息
	selectedUser = mbUser;
	updateUserInfo(mbUser);//检查用户新增粉丝
	userInfo.user = mbUser;//TODO
	
	saveConfig();//保存登录信息
	
	vsControl.selectedIndex = 1;
	vsTitle.selectedIndex = 1;
	listFriends.addMicroBlogListener1();//添加事件侦听
	//重置列表
	reset();
	microBlogAPI.getRateLimitInfo();//获取当前的API调用次数限制.
	//返回用户所有关注的用户最新的n条微博消息
	microBlogAPI.loadFriendsTimeline(friendSinceID,0,fetchSize);//sinceID
	
	//设置自动查询消息
	if(autoRefresh){
		vInterval = setInterval(refreshHandler,vSecs*1000);
	}
}

//清除列表数据
private function reset():void{
	listFriends.reset();
	listAtMe.reset();
	listComments.reset();
	listPrivate.reset();
	listFavorite.reset();
	listUser.reset();
	
	publicSinceID = 0;
	friendSinceID = 0;
	mentionSinceID = 0;
	commentSinceID = 0;
	dmrSinceID = 0;
	userSinceId = 0;	
	userPanel.hideNewFollowers();
}

//设置选项确定后，则调用此方法来更新选项参数
public function updateOptions(vo:OptionVO):void{
	trace("update options..."+vo.toString());
	vSecs = vo.refreshInterval;
	vPopUpDelay = vo.popupDelay;
	
	updateMaxCount(int(so.data["listMaxCount"]));
	
	autoLogin = vo.autoLogin;
	runOnStart = vo.runOnStart;
	popupMsgTip = vo.popupTip;
	soundTip = vo.soundTip;
	listFontSize = vo.fontSize;
	updateListFontSize(listFontSize);
	appAlpha = vo.appAlpha;
	useBgImage = vo.useBgImage;
	useCustomTipSound = vo.useCustomTipSound;
	if(useCustomTipSound){
		dingUrl = vo.dingUrl;
	}else{
		dingUrl = OptionVO.DEFAULT_DING_URL;
	}
	autoSnap = vo.autoSnap;
	
//	if(useBgImage){
//		this.setStyle("borderSkin",BgImage);
//		this.addBgMask();
//	}else{
//		this.setStyle("borderSkin","mainBack");
//	}
	
	this.alpha = appAlpha;
	alwaysInFrontFlag = vo.alwaysInFrontFlag;
	this.alwaysInFront = alwaysInFrontFlag;
	//是否开机启动
	if(!Capabilities.isDebugger){
		this.nativeApplication.startAtLogin = runOnStart;
	}
	
}


private function loginErrorHandler(event:MicroBlogErrorEvent):void
{
	showProgressBar(false);//隐藏登录进度栏
	loginPanel.updateButtonStatus(true);//恢复登录按钮
	trace("login error=>"+event.message);
	FadeToolTip.show("登录新浪微博失败");
}

//显示进度条
public function showProgressBar(value:Boolean,info:String = "",
	hasImage:Boolean=false):void{
	value?ProgressInfo.show(info,hasImage):ProgressInfo.hide();
}


//发布微博成功后的处理
private function updateStatusSucessHandler(microBlogStatus:MicroBlogStatus):void{
	//清空输入
	messageInput.clear();
	imageName=""
	imageByteArray=null;
	//关闭显示的图片预览
	var win:NativeWindow = this.getLikeWindow("预览"); 
	if(win){
		win.close();
		win = null;
	}
	
	//添加新的数据到列表里
	listFriends.addItemAt(microBlogStatus,0);
	messageInput.resizeWindowHandler(false);
	userPanel.updateUserInfo(microBlogStatus.user);
	FadeToolTip.show("发布微博成功！");
}

//返回用户信息成功
private function loadUserInfoSucessHandler(microBlogUser:MicroBlogUser):void{
	trace("load user ok!");
	if(this.logined){
		if(showUserPopup){
			bbControl.selectedIndex = 5;//切换到用户微博列表
			//保存下来
			selectedUser = microBlogUser;
			userInfo.user = selectedUser;
			boxUser.toolTip = selectedUser.screenName+"的微博";
			showProgressBar(true,"正在获取"+selectedUser.screenName+"微博消息...");
			this.loadUserTimeline(selectedUser.screenName);//获取用户的微博消息列表
			//检查一下和该用户的关系
			microBlogAPI.checkIsFollowing(microBlogUser.id,null,mbUser.id,null);
		}else{
			selectedUser = microBlogUser;
			//更新自己的信息
			if(microBlogUser.id == mbUser.id){
				mbUser = microBlogUser;
				updateUserInfo(microBlogUser);
			}else{
				//通过事件发出去，谁需要谁监听
				this.dispatchEvent(new RequestEvent(LOAD_USER_OK,microBlogUser));
			}
		}
	}
	
}

//更新用户信息
private function updateUserInfo(microBlogUser:MicroBlogUser):void{
	var followersKey:String = "followers";
	if(so.data.hasOwnProperty(followersKey)){
		followersCount = so.data[followersKey];
	}else{
		followersCount = mbUser.followersCount; 
	}
	
	if(microBlogUser.followersCount>followersCount){
		//新增粉丝提示
		userPanel.showNewFollowers(microBlogUser.followersCount-followersCount);
		followersCount = microBlogUser.followersCount;//
	}
	//更新用户信息
	userPanel.updateUserInfo(microBlogUser);
	//保存数据
	so.data[followersKey] = followersCount;
	so.flush();
}

//检查与其它用户的关系
private function checkIsFlllowingSucessHandler(microBlogUsersRelationship:MicroBlogUsersRelationship):void{
	var mbrdSource:MicroBlogRelationshipDescriptor = microBlogUsersRelationship.source;
	var mbrdTarget:MicroBlogRelationshipDescriptor = microBlogUsersRelationship.target;
	userInfo.relation = mbrdTarget;
	//显示用户信息
	//var uw:UserInfoWindow = UserInfoWindow.show(selectedUser,mbrdTarget);
}

//返回对微博的转发和评论数
private function loadStatusCountsSucessHandler(values:Array):void{
	switch(vsMain.selectedIndex){
		case 0:
			setStatusCounts(listFriends,values);
			break;
		case 4:
			setStatusCounts(listFavorite,values);
			break;
	}
}

private function getRateLimitStatuSuccessHandler(microBlogRateLimit:MicroBlogRateLimit):void{
	trace("hourlyLimit="+microBlogRateLimit.hourlyLimit+",remainingHits="+microBlogRateLimit.remainingHits);
}



//设置统计的结果信息
private function setStatusCounts(list:MicroBlogList,values:Array):void{
	if(!values) return;
	
	for(var i:int =0;i<values.length;i++){
		var item:Object = new Object();
		item.microBlogCounts = values[i];
		if(list.dataProvider){
			var idx:int = indexOfStatusCounts(list.dataProvider,values[i].id);
			if(idx!=-1){
				Object(list.getChildAt(idx)).data = item;
			}
		}
	}
}


private function indexOfStatusCounts(values:IList,id:uint):int{
	for (var i:int =0;i<values.length;i++){
		if(values.getItemAt(i).id == id){
			return i;
		}
	}
	return -1;
}


//获取对象最大的ID,如果list没有数据，则返回原ID，以保证获取最新的数据
private function getSinceID(list:ArrayList,oldId:uint):uint{
	if(list && list.length>0){
		return list.getItemAt(0).id;
	}
	return oldId;
}


//获取图片查看器窗口
public function getLikeWindow(title:String):NativeWindow{
	for each(var window:NativeWindow in  this.nativeApplication.openedWindows){
		if(window.title.indexOf(title)!=-1){
			return window;
		}
	}
	return null;
}

public function getUserInfoWindow(screenName:String):NativeWindow{
	for each(var window:NativeWindow in  this.nativeApplication.openedWindows){
		if(window.title==screenName){
			return window;
		}
	}
	return null;
}

//取得指定标题的窗口
public function getWindow(title:String):NativeWindow{
	for each(var window:NativeWindow in  this.nativeApplication.openedWindows){
		if(window.title==title){
			return window;
		}
	}
	return null;
}

//发布新微博消息
private function publishHandler(event:RequestEvent):void{
	//去掉多余的空格
	var str:String = Utils.trimStr(String(event.request));
	str = StringUtils.replace(str,"\r","");
	//检查输入字符
	var check:Boolean = Utils.checkInput(str);
	if (!check)
	{
		FadeToolTip.show(mbUser.screenName+"，已经超过140个汉字啦！");
		return;
	}
	
	//判断是否为空
	if (str == "")
	{
		FadeToolTip.show("总得说点什么吧,"+mbUser.screenName+"？");
		return;
	}
	//去除中间的多余空格
	str = Utils.replaceSpace(str);
	imageByteArray?showProgressBar(true,"正在发布...",true):showProgressBar(true,"正在发布...");
	
	microBlogAPI.updateStatus(str,imageName, imageByteArray);
}

//用户意见与建议处理
private function adviceHandler(event:RequestEvent):void{
	//去掉多余的空格
	var str:String = Utils.trimStr(String(event.request));
	str = StringUtils.replace(str,"\r","");
	if (str == ""){
		return;
	}
	//"SnailDesignLab","koma","半杯咖啡Flex"
	var sns:Array = ["SnailDesignLab"];
	var idx:int = 1;
	for each(var name:String in sns){
		if(name!=mbUser.screenName){
			trace("send msg to "+name+" ...");
			microBlogAPI.sendDirectMessage(String(mbUser.id),str,0,name);
		}
		
	}
	
}


//插入表情
private function insertExpression(event:MouseEvent):void{
	
}


//插入图片
private function insertImage(e:RequestEvent):void
{
	var imageFile:File = new File();
	imageFile.browseForOpen("请选择要插入的图片", [new FileFilter("Images", "*.jpg;*.jpeg;*.gif;*.png;")]);
	//监听图片选择事件
	imageFile.addEventListener(Event.SELECT, onImageSelected);
}

//选择插入图片
private function onImageSelected(e:Event):void
{
	//读取image
	imageByteArray = new ByteArray();
	var imageFile:File = e.target as File;
	//读取文件
	readImageFile(imageFile);
	//通知插入了图片
	messageInput.dispatchInsertImage();
}

//读取图片文件，这里写成单独方法便于(1)打开浏览对话框选择 (2)从桌面拖入图片
private function readImageFile(imageFile:File):void{
	var imageStream:FileStream = new FileStream();
	imageStream.open(imageFile, FileMode.READ);
	imageStream.readBytes(imageByteArray, 0, imageStream.bytesAvailable);
	imageStream.close();
	imageName = imageFile.name;
	imageSize = imageFile.size;
	//判断image是否超出大小限制
	if (imageSize > 1000000)
	{
		return;
	}
	//添加默认消息
	if ( Utils.trimStr(messageInput.message) == "" )
	{
		messageInput.message = "分享图片";
		messageInput.checkInput();
	}	
	
	ImageViewer.show("预览图片",imageFile.nativePath,true);
}


//选项下拉菜单
private function dropMenuHandler(event:MouseEvent):void{
	var p:Point = event.target.localToGlobal(new Point());
	var menu:OptionsMenu = OptionsMenu.show(p.x+event.target.width-OptionsMenu.WIN_WIDTH,
		p.y+event.target.height,logined);
	menu.addEventListener(OptionsMenu.CHANGE_MENU,changeMenuHandler);
}

private function dockHandler():void{
	closingHandler(null);//关闭打开的窗口
	this.nativeWindow.visible = false;
	//添加任务栏图标
	addSysTrayIcon();
}

private function exitHandler():void{
	//保存窗口宽度和高度
	so.data["appWidth"] = this.width;
	so.data["appHeight"] = this.height;
	so.flush();
	
	closingHandler(null);
	microBlogAPI.logout();//退出
	this.exit();
}

//从系统托盘恢复到任务栏
public function undockHandler():void{
	this.nativeWindow.visible = true;
	this.nativeApplication.icon.bitmaps = [];
	//激活所有打开的窗口
	activateAll();
	//窗口提到最前面
	this.nativeWindow.orderToFront();
}

//最大化处理
private function  maximizeHandler():void{
	maxed = !maxed;
	if(maxed){
		var xw:int = 30;
		var yw:int = 40;
		var relX:Number = Capabilities.screenResolutionX;
		var relY:Number = Capabilities.screenResolutionY;
		this.nativeWindow.x = xw;
		this.nativeWindow.y = 0;
		this.width = relX - xw * 2;
		this.height = relY - yw *2;
	}else{
		this.nativeWindow.x = 20;
		this.nativeWindow.y = 20;
		this.width = 340;
		this.height = 650;
	}
}
//最小化到任务栏
private function  minimizeHandler():void{
	/* if(isSnaped){
		var relX:Number = Capabilities.screenResolutionX;
		switch(snapDirection){
			case SNAP_TOP:			
				this.nativeWindow.y = -35;
				break;
			case SNAP_LEFT:
				this.nativeWindow.x = -8;
				break;
			case SNAP_RIGHT:
				this.nativeWindow.x = relX - this.width+10;
				break;
		}
		this.nativeWindow.y = -35;
	} */
	this.minimize();
}

private function activateAll():void{
	this.activate();
	this.nativeWindow.activate();
}

/********************************* 系统托盘图标处理 ************************************/
//添加系统托盘图标,windows环境
private function addSysTrayIcon(newMsg:Boolean=false):void{
	if(NativeApplication.supportsSystemTrayIcon){
		var sti:SystemTrayIcon = SystemTrayIcon(this.nativeApplication.icon);

		if(newMsg){
			var icon16:Class = CSSParser.getStyle(".appIcon16Coming","icon");
			this.nativeApplication.icon.bitmaps = [new icon16()];
			sti.tooltip = "Splus微博 - 有新微博消息！";
		}else{
			var icon16:Class = CSSParser.getStyle(".appIcon16","icon");
			this.nativeApplication.icon.bitmaps = [new icon16()];
			sti.tooltip = "Splus微博 - 新浪微博客户端";
		}
		sti.menu = createSysTrayMenu();
		//单击系统托盘图标时恢复窗口
		sti.addEventListener(MouseEvent.CLICK,restoreFromSysTrayHandler);
	}else if(NativeApplication.supportsDockIcon){//MAC OS & Linux
		var dock:DockIcon = DockIcon(this.nativeApplication.icon);
		var icon16:Class = CSSParser.getStyle(".appIcon16","icon");
		this.nativeApplication.icon.bitmaps = [new icon16()];
		dock.menu = createSysTrayMenu();
		dock.addEventListener(InvokeEvent.INVOKE,restoreFromSysTrayHandler);
	}
}

//创建系统托盘图标上下文菜单
private function createSysTrayMenu():NativeMenu{
	var menu:NativeMenu = new NativeMenu();
	var labels:Array = ["打开","刷新","SnailDesign.com","","退出Splus微博客户端"];
	var names:Array = ["mnuOpen","mnuRefresh","mnuSd","mnuSep1","mnuExit"];
	for (var i:int = 0;i<labels.length;i++){
		//如果标签为空的话，就任为是分隔符
		var menuItem:NativeMenuItem = new NativeMenuItem( labels[i],labels[i]=="");
		menuItem.name = names[i];
		menuItem.addEventListener(Event.SELECT,sysTrayMenuHandler );
		menu.addItem( menuItem );				
	}
	
	return menu;
}

//系统托盘菜单事件
private function sysTrayMenuHandler(event:Event):void{
	switch(event.target.name){
		case "mnuOpen":
			undockHandler();
			break;
		case "mnuRefresh":
			refreshButtonHandler();
			break;
		case "mnuSd":
			navigateToURL(new URLRequest("http://www.snaildesign.com"),"_blank");
			break;
		case "mnuExit":
			exitHandler();
			break;
	}
	
}

//系统托盘图标单击事件
private function restoreFromSysTrayHandler(event):void{
	undockHandler();
}

//标题栏拖动
private function startDragHandler(event:MouseEvent):void{
	if(!(event.target is Button) && !(event.target is Text) && !(event.target is Label) &&
		!(event.target is UITextField) && !(event.target is FlexLoader) &&
		!(event.target is InfoNumber)){
		this.nativeWindow.startMove();
		this.alpha = 0.5;
	}
	//保存原始窗口位置
	oldX = this.nativeWindow.x;
	oldY = this.nativeWindow.y;		
}

private function stopDragHandler():void{
	this.alpha = appAlpha;
	//自动吸附计算
	var newX:Number = this.nativeWindow.x;
	var newY:Number = this.nativeWindow.y;
	var relX:Number = Capabilities.screenResolutionX;
	
	isMoved = ((Math.abs(newX-oldX)>=minMovedSize) || (Math.abs(newY-oldY)>=minMovedSize));
	if(autoSnap && isMoved && isPopUpText==false){
		if(this.nativeWindow.y<snapDistance){
			isSnaped = true;
			snapDirection = SNAP_TOP;
			hideWindow();
		}else if(this.nativeWindow.x<snapDistance){
			isSnaped = true;
			snapDirection = SNAP_LEFT;
			hideWindow();
		}else if(this.nativeWindow.x>relX-this.width){
			isSnaped = true;
			snapDirection = SNAP_RIGHT;
			hideWindow();
		}else{
			isSnaped = false;
			btnbtnMinimize.visible = btnbtnMinimize.includeInLayout = true;
		}
		
		this.alwaysInFront = isSnaped;
		if(alwaysInFrontFlag){
			this.alwaysInFront = true;
		}
	}	
}

//显示主窗口
private function showMainWindow(event:MouseEvent):void{
	if(isSnaped && isPopUpText==false){
		switch(event.type){
			case MouseEvent.ROLL_OVER:
				showWindow();
				break;
			case MouseEvent.ROLL_OUT:
				hideWindow();
				break;
		}
	}

}

private function popUpWinHandler(event:Event):void{
	isPopUpText = (event.type == MicroBlogList.POP_UP_WIN);
}

//隐藏窗口
private function hideWindow():void{
	removeShowWindowHandler();//防止窗口闪烁
	var relX:Number = Capabilities.screenResolutionX;
	var m:Move = new Move(this);
	m.addEventListener(EffectEvent.EFFECT_END,addShowWindowHandler);
	switch(snapDirection){
		case SNAP_TOP:
			m.xFrom = this.nativeWindow.x;
			m.yFrom =  this.nativeWindow.y;
			m.xTo = this.nativeWindow.x;
			m.yTo =  snapDistance - this.height+6;				
			break;
		case SNAP_LEFT:
			m.xFrom = this.nativeWindow.x;
			m.yFrom =  this.nativeWindow.y;
			m.xTo = - this.width + 10;
			m.yTo =  this.nativeWindow.y;	
			break;
		case SNAP_RIGHT:
			m.xFrom = this.nativeWindow.x;
			m.yFrom =  this.nativeWindow.y;
			m.xTo = relX - 10;
			m.yTo =  this.nativeWindow.y;					
			break;
	}
	m.play(); 
	
	btnbtnMinimize.visible = btnbtnMinimize.includeInLayout = false;
}

public function removeShowWindowHandler():void{
	this.removeEventListener(MouseEvent.ROLL_OVER,showMainWindow);
	this.removeEventListener(MouseEvent.ROLL_OUT,showMainWindow);
}

public function addShowWindowHandler(event:EffectEvent):void{
	this.addEventListener(MouseEvent.ROLL_OVER,showMainWindow);
	this.addEventListener(MouseEvent.ROLL_OUT,showMainWindow);	
}

//显示窗口
private function showWindow():void{
	var relX:Number = Capabilities.screenResolutionX;
	var m:Move = new Move(this);
	switch(snapDirection){
		case SNAP_TOP:			
			m.xFrom = this.nativeWindow.x;
			m.yFrom = this.nativeWindow.y;
			m.xTo = this.nativeWindow.x;
			m.yTo = -35;
			break;
		case SNAP_LEFT:
			m.xFrom = this.nativeWindow.x;
			m.yFrom =  this.nativeWindow.y;
			m.xTo = -8;
			m.yTo =  this.nativeWindow.y;	
			break;
		case SNAP_RIGHT:
			m.xFrom = this.nativeWindow.x;
			m.yFrom =  this.nativeWindow.y;
			m.xTo = relX - this.width+10;
			m.yTo =  this.nativeWindow.y;					
			break;
	}
	m.play();
}
//改变输入框大小
private function changeInputHandler(event:RequestEvent):void{
	var h:Number = Number(event.request);
	if(h!=messageInput.maxChangeHeight){
		messageInput.resizeWindowHandler(true);
	}
}

//删除选择的图片
private function deleteImageHandler(event:Event):void{
	imageName=""
	imageByteArray=null;	
}

//从剪切板里粘贴图片数据
private function pasteBMPHandler(event:Event):void{
	var bmpData:BitmapData = Clipboard.generalClipboard.getData(ClipboardFormats.BITMAP_FORMAT) as BitmapData;
	var bmp:Bitmap = new Bitmap(bmpData);
	imageName = "fromClipboard";
	var jpgEncoder:JPEGEncoder = new JPEGEncoder(85);
	imageByteArray = jpgEncoder.encode(bmpData);
	ImageViewer.show("截屏图片预览",null,true,bmp);
	if(messageInput.message == ""){
		messageInput.message = "分享截图";
	}
	
	//通知插入了图片
	messageInput.dispatchInsertImage();	
}

private function hideMessageInput():void{
	if(messageInput.opened){
		bbControl.setFocus();
		messageInput.resizeWindowHandler(false);
	}
}
//取得输入消息框的纵坐标位置
public function getMessageInputY():Number{
	var p:Point = messageInput.localToGlobal(new Point());
	return p.y;
}
//批量统计微薄的评论数
private function loadStatusInfoHandler(dataProvider:IList):void{
	var ids:Array = new Array();
	for (var i:int =0;i<dataProvider.length;i++){
		ids.push(dataProvider.getItemAt(i).id);
	}
	microBlogAPI.loadStatusCounts(ids);
}

/********************************* 自动升级处理 ************************************/
//版本检查
public function checkVersion(autoCheck:Boolean = true):void{
	this.autoCheck = autoCheck;
	//http://snaildesign.googlecode.com/files/update.xml
	//http://www.snaildesign.com/upload/update/splus/update.xml
	//http://snaildesign.googlecode.com/files/update.xml
	updateUtil = new UpdateUtil(updateUrl,updateHandler);
}

//升级处理
private function updateHandler(event:Event):void{
	switch(event.type){
		case StatusUpdateEvent.UPDATE_STATUS:
			event.preventDefault();//阻止系统自动更新
			var evt:StatusUpdateEvent = StatusUpdateEvent(event);
			if(evt.available){
				var s:String = "    Splus有新版本 "+evt.version+" 可更新,要下载吗？\n";
				var ary :Array = evt.details[0];
				s += "    "+ary.join("")+"\n\n";
				s += "    当前版本:"+updateUtil.updater().currentVersion;
				//AlertX.confirm(s,confirmHandler,"检查新版本",false);
				var vc:VersionCheck = VersionCheck.show(s);
				vc.addEventListener(VersionCheck.DOWNLOAD,downloadHandler);
			}else{
				if(!autoCheck){
					FadeToolTip.show("当前已经是最新版本。");
				}
			}
			break;
		case ProgressEvent.PROGRESS:
			showDownloadProgress(true);
			var pEvent:ProgressEvent = ProgressEvent(event);
			progressDownload.setProgress(pEvent.bytesLoaded,pEvent.bytesTotal);
			break;
		case UpdateEvent.DOWNLOAD_COMPLETE:
			showDownloadProgress(false);
			break;
		case ErrorEvent.ERROR:
		case StatusUpdateErrorEvent.UPDATE_ERROR:
			FadeToolTip.show("版本检查异常，请稍候再试。");
			break;
	}
}

//开始下载
private function downloadHandler(event:Event):void{
	updateUtil.updater().downloadUpdate();
}

//显示下载进度条
private function showDownloadProgress(visible:Boolean):void{
	boxProgress.visible = boxProgress.includeInLayout = visible;
}
//确认更新
private function confirmHandler(event:CloseEvent):void{
	
	if(event.detail == AlertX.YES){
		updateUtil.updater().downloadUpdate();
	}
}
//获取当前版本
public function getVersion():String{
	return updateUtil.updater().currentVersion;
}

//快捷键处理
var verticalPos:Number = 0;
private function shortCutHandler(event:KeyboardEvent):void{
	var list:MicroBlogList = getMicroBlogList(vsMain.selectedIndex);
	switch(event.keyCode){
		case Keyboard.ESCAPE://最小化
			dockHandler();
			break;
		case Keyboard.INSERT://焦点设置为发布输入框
//		case Keyboard.ENTER://回车键
			messageInput.txtMsg.setFocus();
			break;
		case Keyboard.F3://最小化与最大化之间切换
			if(this.nativeWindow.visible){
				dockHandler();
			}else{
				undockHandler();
			}
			break;
		case Keyboard.F5://刷新
			showProgressBar(true);
			refresh(bbControl.selectedIndex,true);
			break;
		case Keyboard.F6://调试，日志打印
			debugInfo();
			break;
		case Keyboard.HOME://列表最上
			verticalPos = 0;
			list.verticalScrollPosition = verticalPos;
			break;
		case Keyboard.END://列表最下
			verticalPos = list.maxVerticalScrollPosition;
			list.verticalScrollPosition = verticalPos;
			break;
		case Keyboard.PAGE_UP://列表向上
			verticalPos -= (list.height - 10);
			if(verticalPos<0){
				verticalPos = 0;
			}
			list.verticalScrollPosition = verticalPos;
			break;
		case Keyboard.PAGE_DOWN://列表向下
//		case Keyboard.SPACE://空格键
			verticalPos += (list.height - 10);
			if(verticalPos>list.maxVerticalScrollPosition){
				verticalPos = list.maxVerticalScrollPosition;
			}
			list.verticalScrollPosition = verticalPos;
			break;
	}
	
}

//调试时trace
private function debugInfo():void{
	var s:String = "";
	s = "firends="+listFriends.numChildren+",comments="+listComments.numChildren+",directMsg="+listPrivate.numChildren+",";
	s += "user="+listUser.numChildren+"\n";
	s += "MicroMsgItemCache="+MicroMsgItemCache.cache.length+
		",MicroMsgCommentItemCache="+MicroMsgCommentItemCache.cache.length+
		",MicroMsgPrivateItemCache="+MicroMsgPrivateItemCache.cache.length;
	trace(s);
}


//根据昵称获取用户信息,showUserPopup:是否显示用户弹出信息窗口
private var userWinRelated:NativeWindow;
public function loadUserInfo(screenName:String,showUserPopup:Boolean=true,target:NativeWindow=null):void{
	if(!target){
		target = this.nativeWindow;
	}
	userWinRelated = target;
	this.showUserPopup = showUserPopup;
	showProgressBar(showUserPopup);
	microBlogAPI.loadUserInfo(null,0,screenName);
}

//根据ID来查找用户
public function loadUserInfoByID(userID:uint,showUserPopup:Boolean = true):void{
	this.showUserPopup = showUserPopup;
	showProgressBar(showUserPopup);
	microBlogAPI.loadUserInfo(null,userID);
}

//设置所有消息为已读
private function readAllHandler(event:Event):void{
	switch(event.target){
		case infoHome:
			listFriends.readAll();
			infoHome.hide();
			break;
		case infoComment:
			listComments.readAll();
			infoComment.hide();
			break;
		case infoDirectMsg:
			listPrivate.readAll();
			infoDirectMsg.hide();
			break;
	}
}
//更新消息数显示
private function showNewMsgCountHandler(event:RequestEvent):void{
	//如果是F5刷新获取，则不提示，并标记为已读状态，仅仅是更新时间
	trace("reloadAll="+reloadAll);
	if(reloadAll) {
		listFriends.readAll();
		infoHome.hide();
		listComments.readAll();
		infoComment.hide();
		listPrivate.readAll();
		infoDirectMsg.hide();
		return;
	}
	
	var count:int = int(event.request);
	switch(event.target){
		case listFriends:
			showInfoNum(count,infoHome);
			break;
		case listComments:
			showInfoNum(count,infoComment);
			break;
		case listPrivate:
			showInfoNum(count,infoDirectMsg);
			break;
	}
}

//显示消息数
private function showInfoNum(count:int,infoNumber:InfoNumber):void{
	if(count>0){
		var button:Button = Button(bbControl.getChildAt(infoNumber.index));
		var p:Point = new Point(button.x+button.width-infoNumber.width,
								button.y+button.height-infoNumber.height);
		infoNumber.show(p,count.toString());
	}else{
		infoNumber.hide();
	}
}

public function getSharedObject():SharedObject{
	return so;
}

public function getSoUrl():String{
	return this.soUrl;
}

//批量更新列表中微博的时间信息
private function updateStatusCreateTime(list:MicroBlogList):void{
	for each(var item:Object in list.getChildren()){
		var id:int = item.getData().id;
		microBlogAPI.loadStatusInfo(id);
	}
}

//更新时间戳
private function updateCreateTime(microBlogStatus:MicroBlogStatus):void{
	switch(vsMain.selectedIndex){
		case 0:
			listFriends.updateCreateTime(microBlogStatus.id);
			break;
		case 1:
			break;
		case 2:
			break;
		case 3:
			break;
		case 4:
			break;
		case 5:
			break;
	}
}

//翻页处理
private function pagerHandler(event:Event):void{
	showProgressBar(true);
	pager.setEnabled(false);//禁用翻页
	isPaging = true;//正在翻页
	switch(vsMain.selectedIndex){
		case 0://主页
			friendPage = pageIndexHandler(event.type,friendPage);
			microBlogAPI.loadFriendsTimeline(0,0,fetchSize,friendPage);
			listFriends.page = friendPage;
			break;
		case 1://提到我的
			atMePage = pageIndexHandler(event.type,atMePage);
			microBlogAPI.loadMentions(0,0,fetchSize,atMePage);
			listAtMe.page = atMePage;
			break;
		case 2://评论
			commentsPage = pageIndexHandler(event.type,commentsPage);
			microBlogAPI.loadCommentsTimeline(0,0,fetchSize,commentsPage);
			listComments.page = commentsPage;
			break;
		case 3://我的私信
			switch(event.type){
				case Pager.GET_PAGE:
					directMsgPage = 1;
					microBlogAPI.loadDirectMessagesReceived(0,0,fetchSize,directMsgPage);
					break;
				case Pager.SEND_PAGE:
					directMsgPage = 1;
					microBlogAPI.loadDirectMessagesSent(0,0,fetchSize,directMsgPage);
					break;
				default:
					switch(pager.currentType){
						case Pager.GET_PAGE:
							directMsgPage = pageIndexHandler(event.type,directMsgPage);
							microBlogAPI.loadDirectMessagesReceived(0,0,fetchSize,directMsgPage);
							listPrivate.page = directMsgPage;
							break;
						case Pager.SEND_PAGE:
							directMsgPage = pageIndexHandler(event.type,directMsgPage);
							microBlogAPI.loadDirectMessagesSent(0,0,fetchSize,directMsgPage);
							listPrivate.page = directMsgPage;
							break;
					}
					break;
			}
			break;
		case 4://我的收藏
			myFavoritePage = pageIndexHandler(event.type,myFavoritePage);
			microBlogAPI.loadFavoriteList(myFavoritePage);
			listFavorite.page = myFavoritePage;
			break;
		case 5://我&&用户的微博
			usersPage = pageIndexHandler(event.type,usersPage);
			var tmpUser:MicroBlogUser;
			if(listUser.dataProvider && listUser.dataProvider.length>0){
				tmpUser = MicroMsgItem(listUser.getChildAt(0)).getData().user;
			}else{
				tmpUser = mbUser;
			}
			
			microBlogAPI.loadUserTimeline(null,0,tmpUser.screenName,0,0,fetchSize,usersPage);
			listUser.page = usersPage;
			break;
	}
}
//翻页数处理
private function pageIndexHandler(type:String,page:int):int{
	switch(type){
		case Pager.FIRST_PAGE:
			page = 1;
			break;
		case Pager.PRIOR_PAGE:
			page--;
			if(page<1){
				page = 1;
			}
			break;
		case Pager.NEXT_PAGE:
			page++;
			break;
	}
	pager.setButtonVisible(page);
	return page;
}

public function get popUpDelay():int{
	return this.vPopUpDelay;
}

//搜索处理
private function showSearchBar(event:MouseEvent):void{
	SearchBar.show(event.target as Button);
}

private function resetPagerHandler(event:ResizeEvent):void{
	pager.visible = true;
	var p:Point = messageInput.localToGlobal(new Point());
	pager.x = p.x +messageInput.width - pager.width - 16;
	pager.y = p.y - pager.height;
}

//播放新消息声音提示
var song:SoundChannel;
var soundFactory:Sound = new Sound();
private function playDingDong():void{
	var request:URLRequest = new URLRequest(dingUrl);
	if(soundFactory.hasEventListener(IOErrorEvent.IO_ERROR)==false){
		soundFactory.addEventListener(IOErrorEvent.IO_ERROR,loadSoundHandler);
	}
    soundFactory.load(request);
    song = soundFactory.play();
}

private function loadSoundHandler(event:IOErrorEvent):void{
	FadeToolTip.show("播放自定义提示音文件失败，请检查声音文件是否存在！");
}

//对TA说
public function atTaHandler(ta:String):void{
	messageInput.resizeWindowHandler(true);
	messageInput.message = messageInput.message+"@"+ta+"：";
	messageInput.selectionLast();
}

//加载通知信息begin-------------------------------------------------------------
private function loadNotice():void{
	loader = new LoadXMLDelegate(this,noticeUrl,"object");
	loader.load();	
}

//返回结果处理
private var notices:Array;
private var urlLoader:URLLoader = new URLLoader();
public function result(r:Object):void{
	if(r.result.notices.notice){
		notices = ArrayCollection(r.result.notices.notice).toArray();
	}
	
	var str:String = "";
	for each(var s:String in notices){
		str += s +"\n";
	}
	loginPanel.txtNotice.htmlText = str;
	
	var logo:Object = r.result.notices.logo;
	if(logo && logo.url && logo.url!=""){
		loginPanel.imgLogo.source = logo.url;
		loginPanel.imgLogo.toolTip = logo.tip;
		loginPanel.imgLogo.addEventListener(Event.COMPLETE,loadLogoHandler);
		loginPanel.imgLogo.addEventListener(IOErrorEvent.IO_ERROR,loadLogoHandler);
	}
}

private function loadLogoHandler(event:Event):void{
	switch(event.type){
		case Event.COMPLETE:
			loginPanel.imgLogo.visible = loginPanel.imgLogo.includeInLayout = true;
			loginPanel.boxLogo.setStyle("borderSkin",null);
			break;
		case IOErrorEvent.IO_ERROR:
			loginPanel.imgLogo.visible = loginPanel.imgLogo.includeInLayout = false;
			break;
	}
	
}



public function fault(f:Object):void{
	if(f is FaultEvent){
		trace("load notices ERROR ,"+ObjectUtil.toString(FaultEvent(f).fault));
	}
}


//加载通知信息end-------------------------------------------------------------

private function showHotWindowHandler():void{
	var hotWindow:HotWindow = HotWindow.show();
	hotWindow.height = this.height-30;
	hotWindow.width = 560;
	Utils.resetWindowPos(this.nativeWindow,hotWindow);
}

//更换背景图片start---------------------------------------------------------------
//用作蒙板的画布对象，处理自定义背景问题
private function generateBgMask():Canvas{
	//封闭矩形的8个点位置
	var points:Array = new Array();
	points.push(new Point(0,35));
	points.push(new Point(10,35));
	points.push(new Point(10,21));
	points.push(new Point(62,21));
	points.push(new Point(62,35));
	points.push(new Point(this.width,35));
	points.push(new Point(this.width,this.height));
	points.push(new Point(0,this.height));
	
	//用于散板的画布
	var cav:Canvas = new Canvas();
	var g:Graphics = cav.graphics;
	g.lineStyle(1);
	g.beginFill(0xFFFFFF);
	//画封闭多边形
	g.moveTo(points[0].x,points[0].y);
	for each(var p:Point in points){
		g.lineTo(p.x,p.y);
	}
	
	g.endFill();
	return cav;
}

//登录前的蒙板，因为登录后有头像部分突出了
private function generateBgMaskLogin():Canvas{
	//用于蒙板的画布
	var cav:Canvas = new Canvas();
	var g:Graphics = cav.graphics;
	g.lineStyle(1);
	g.beginFill(0xFFFFFF);
	g.drawRect(0,35,this.width,this.height);
	g.endFill();
	return cav;
}


//添加背景蒙板
private function addBgMask():void{
	var cav:Canvas = logined?generateBgMask():generateBgMaskLogin();
	cav.visible = false;
	cav.includeInLayout = false;
	this.mask = cav;	
}

//更换背景
private function changeBackgroundImage(vent:MouseEvent):void{
	var imageFile:File = new File();
	imageFile.browseForOpen("请选择要作为背景的图片", [new FileFilter("Images", "*.jpg")]);
	//选择图片后的处理
	imageFile.addEventListener(Event.SELECT, onBgImageSelected);
}

private function onBgImageSelected(event:Event):void{
	var sourceFile:File = event.target as File;
	var rootDir:File = File.applicationDirectory;
	var destFile:File = new File(rootDir.nativePath+"/assets/BgImage.jpg");
	sourceFile.copyTo(destFile,true);
	
	this.setStyle("borderSkin",BgImage);
	this.addBgMask();
	
	so.data["useBgImage"]=true;
	so.flush();
}

//更换背景图片end---------------------------------------------------------------

private function resizeWinHandler(event:ResizeEvent):void{
	if(useBgImage){
		//添加背景蒙板
		addBgMask();
	}
}

//更换背景图片end---------------------------------------------------------------
private function showProfileImageHandler(event:RequestEvent):void{
	switch(event.type){
		case MicroMsgItem.SHOW_PROFILE_IMAGE:
			var imgOwner:Object = event.request.owner;
			var profileImageUrl:String = String(event.request.profileImageUrl);
			var upi:UserProfileImage = UserProfileImage.show(profileImageUrl,180);
			resetProfileImage(imgOwner,upi);
			break;
		case MicroMsgItem.HIDE_PROFILE_IMAGE:
			UserProfileImage.hide();
			break;
	}
}

//设置弹出的用户头像位置
private function resetProfileImage(owner:Object,upi:UserProfileImage):void{
	var p:Point = owner.localToGlobal(new Point());
	var xn:Number = p.x+owner.width;
	var yn:Number = p.y;
	if((yn+upi.height)>this.height){
		yn = this.height - upi.height - 10;
	}
	upi.x = xn;
	upi.y = yn;
}

